package com.paipai.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.paipai.dao.*;
import com.paipai.dto.RoundVo;
import com.paipai.entity.*;
import com.paipai.es.RoundES;
import com.paipai.es.RoundRepository;
import com.paipai.utils.IdWorker;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class RoundService {
    @Autowired
    @Qualifier("idWorker2")
    private IdWorker idWorker2;
    @Autowired
    RoundMapper roundMapper;
    @Autowired
    ProductMapper productMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    PtypeMapper ptypeMapper;
    @Autowired
    RoundRepository roundRepository;

    public PageInfo<RoundVo> roundPage(Integer pageSize, Integer pageNumber, String state) {
        PageHelper.startPage(pageNumber, pageSize);
        Round roundProp = new Round();
        if (!"0".equals(state)) {
            roundProp.setState(state);
        }
        List<Round> rounds = roundMapper.select(roundProp);
        PageInfo<Round> roundPageInfo = new PageInfo<Round>(rounds);
        //将 List<Round>封装为 List<RoundVo>
        List<RoundVo> roundVoList = new ArrayList<RoundVo>();
        for (Round round : rounds) {
            //根据商品id查询出商品对象
            Product productPro = new Product();
            productPro.setId(round.getProductid());
            Product product = productMapper.selectOne(productPro);
            //根据商品id 查询出 类型对象
            Ptype ptypePro = new Ptype();
            ptypePro.setId(product.getTypeid());
            Ptype ptype = ptypeMapper.selectOne(ptypePro);
            //根据 商品对象拿到用户id查询出user对象
            User userPro = new User();
            userPro.setId(product.getSalerid());
            User user = userMapper.selectOne(userPro);
            String imgs = product.getImgs();
            String[] split = null;
            if (!StringUtils.isEmpty(imgs)) {
                split = imgs.split(";");
            }
            RoundVo roundVo = new RoundVo();
            roundVo.setPname(product.getName());
            roundVo.setTypeNmae(ptype.getTypename());
            roundVo.setSalerName(user.getName());
            roundVo.setId(round.getId());
            roundVo.setProductid(round.getProductid());
            roundVo.setSalerid(round.getSalerid());
            roundVo.setUserid(round.getUserid());
            roundVo.setDeposit(round.getDeposit());
            roundVo.setStartprice(round.getStartprice());
            roundVo.setStepprice(round.getStepprice());
            roundVo.setFinalprice(round.getFinalprice());
            roundVo.setDuration(round.getDuration());
            roundVo.setStarttime(round.getStarttime());
            roundVo.setState(round.getState());
            roundVo.setLookeramount(round.getLookeramount());
            roundVo.setCallamount(round.getCallamount());
            //图片集合
            List<String> srcList = new ArrayList<String>();
            for (String s : split) {
                srcList.add(s);
            }
            roundVo.setProductSrcs(srcList);
            roundVoList.add(roundVo);
        }
        PageInfo<RoundVo> roundVoPageInfo = new PageInfo<RoundVo>(roundVoList);
        roundVoPageInfo.setPages(roundPageInfo.getPages());
        roundVoPageInfo.setTotal(roundPageInfo.getTotal());
        roundVoPageInfo.setPageNum(pageNumber);
        roundVoPageInfo.setPageSize(pageSize);
        return roundVoPageInfo;
    }

    public PageInfo<RoundES> roundESPage(Integer pageSize, Integer currentPage, String keyword) {
        //构件查询条件对象
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //query条件
        nativeSearchQueryBuilder.withQuery(QueryBuilders.multiMatchQuery(keyword, "pname", "typeNmae", "pdetail", "salerName"));
        //分页条件   es里面分页页码从0开始
        nativeSearchQueryBuilder.withPageable(PageRequest.of(currentPage - 1, pageSize));
        //排序条件
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("lookeramount").order(SortOrder.DESC));
        //查询
        org.springframework.data.domain.Page<RoundES> search = roundRepository.search(nativeSearchQueryBuilder.build());
        //将es的page 替换成mybatisplus 的page对象
        PageInfo<RoundES> pageInfo=new PageInfo<>();
        pageInfo.setTotal(search.getTotalElements());
        pageInfo.setPages(search.getTotalPages());
        pageInfo.setPageSize(pageSize);
        pageInfo.setPageNum(currentPage);
        pageInfo.setList(search.getContent());
        return pageInfo;
    }
    /**
     * 根据场次id查询返回roundVo类
     * @param roundId
     * @return
     */
    public RoundVo getRoundById(long roundId) {
        Round round = new Round();
        round.setId(roundId);
        //根据传入id查询对应场次
        Round round1 = roundMapper.selectOne(round);
        Product product = new Product();
        product.setId(round1.getProductid());
        //根据商品id查询对应商品信息 封装进vo
        Product product1 = productMapper.selectOne(product);
        //封装图片 用；进行分割的
        String[] pics = null;
        if (!StringUtils.isEmpty(product1.getImgs())) {
            pics = product1.getImgs().split(";");
        }
        List<String> srcs = new ArrayList<>();
        for (String pic : pics) {
            srcs.add(pic);
        }
        //封装类型名
        Ptype type = new Ptype();
        type.setId(product1.getTypeid());
        Ptype type1 = ptypeMapper.selectOne(type);
        RoundVo roundVo = new RoundVo();
        //封装卖家姓名
        User user = new User();
        user.setId(round1.getSalerid());
        User user1 = userMapper.selectOne(user);
        roundVo.setPname(product1.getName());
        roundVo.setProductSrcs(srcs);
        roundVo.setTypeNmae(type1.getTypename());
        roundVo.setSalerName(user1.getName());
        roundVo.setId(round1.getId());
        roundVo.setState(round1.getState());
        roundVo.setStarttime(round1.getStarttime());
        roundVo.setFinalprice(round1.getFinalprice());
        roundVo.setDuration(round1.getDuration());
        roundVo.setUserid(round1.getUserid());
        roundVo.setCallamount(round1.getCallamount());
        roundVo.setLookeramount(round1.getLookeramount());
        roundVo.setDeposit(round1.getDeposit());
        roundVo.setStartprice(round1.getStartprice());
        roundVo.setProductid(round1.getProductid());
        roundVo.setSalerid(round1.getSalerid());
        roundVo.setStepprice(round1.getStepprice());
        return roundVo;
    }

    public String publish(Long userId,Long productId, String deposit, String startPrice, String stepPrice, String duration, Date startTime){
        String regex = "^[0-9]+(\\.[0-9]{1,2})?$";
        if(productId == null) return "竞拍商品不能为空!";
        if(deposit == null || !deposit.matches(regex)) return "押金格式错误，请重新输入！";
        if(deposit.equals("0")) return "押金不能为0！";
        if(startPrice == null || !startPrice.matches(regex)) return "起拍价格格式错误，请重新输入!";
        if(startPrice.equals("0")) return "起拍价格不能为0！";
        if(stepPrice == null || !stepPrice.matches(regex)) return "加价幅度格式错误，请重新输入!";
        if(stepPrice.equals("0")) return "加价幅度不能为0！";
        if(Objects.equals(duration,"") || !duration.matches(regex)) return "竞拍天数格式错误，请重新输入!";
        if(duration.equals("0")) return "竞拍天数不能为0！";
        if(startTime == null) return "开始时间不能为空!";
        if(startTime.before(new Date())) return "开始时间应该晚于当前时间！请重新选择！";

        //--将字符串转换成BigDecimal类型
        BigDecimal deposit1 = new BigDecimal(deposit);
        BigDecimal startPrice1 = new BigDecimal(startPrice);
        BigDecimal stepPrice1 = new BigDecimal(stepPrice);
        synchronized(this) {
            Round round = new Round();
            round.setId(idWorker2.nextId());
            round.setProductid(productId);
            round.setSalerid(userId);
            round.setDeposit(deposit1);
            round.setStartprice(startPrice1);
            round.setStepprice(stepPrice1);
            round.setDuration(duration);
            round.setStarttime(startTime);
            round.setState("1");
            round.setCallamount(0);
            roundMapper.insert(round);

            //--修改product表中的商品状态
            modifyStateById(productId,1);
        }
        return "恭喜您发布成功!!!";
    }
    //--id state
    public int modifyStateById(Long productId,Integer state){
        Product product = productMapper.selectByPrimaryKey(productId);
        product.setUpdatetime(new Date());
        product.setState(state);
        return productMapper.updateByPrimaryKey(product);
    }
}
